from contextlib import contextmanager

from sqlalchemy.orm import Session

from core.config.mysql_config import MySQLConfig
from service.database_service.mysql.models.tables import Publisher

class PublisherCRUD:
    def __init__(self):
        pass

    @staticmethod
    def get_all_publisher(db: Session):
        return db.query(Publisher).all()

    @staticmethod
    def get_publisher_by_name(db: Session, publisher_name: str):
        return db.query(Publisher).filter(Publisher.publisher_name == publisher_name).first()

    @staticmethod
    def update_publisher(db: Session, new_publisher: Publisher):
        update_num = db.query(Publisher).filter(Publisher.publisher_name == new_publisher.publisher_name).update(
            {
                Publisher.publisher_total_fans: new_publisher.publisher_total_fans,
                Publisher.publisher_total_article: new_publisher.publisher_total_article,
            }
        )
        db.commit()
        return update_num

    @staticmethod
    def batch_insert_publishers(db: Session, publishers_data: list[dict]) -> int:
        # 将字典数据转换为 Publisher 对象
        publishers = [
            Publisher(
                publisher_name=data["publisher_name"],
                publisher_url=data["publisher_url"],
                publisher_location=data["publisher_location"],
                publisher_total_article=data.get("publisher_total_article", 0),
                publisher_total_fans=data.get("publisher_total_fans", 0),
            )
            for data in publishers_data
        ]

        db.add_all(publishers)
        db.commit()
        return len(publishers_data)

    @staticmethod
    def insert_one_publisher(db: Session, data: dict) -> Publisher:
        publisher = Publisher(
            publisher_name=data["publisher_name"],
            publisher_url=data["publisher_url"],
            publisher_location=data["publisher_location"],
            publisher_total_article=data.get("publisher_total_article", 0),
            publisher_total_fans=data.get("publisher_total_fans", 0),
        )
        db.add(publisher)
        db.commit()
        db.refresh(publisher)
        return publisher

if __name__ == '__main__':
    # @contextmanager
    # def get_db():
    #     db = MySQLConfig().get_redis_client()
    #     try:
    #         yield db
    #         db.commit()
    #     except Exception as e:
    #         db.rollback()
    #         raise
    #     finally:db.close()
    #
    @contextmanager
    def up_db():
        db = MySQLConfig().get_redis_client()
        try:
            yield db
            db.commit()
        except Exception as e:
            db.rollback()
            raise
        finally:
            db.close()

    # with get_db() as db:
    #     new_publisher = PublisherCRUD.get_publisher_by_id(db, 1)
    #     print(new_publisher)
    #     all = PublisherCRUD.get_all_publisher(db)
    #     print(all)
    with up_db() as db:
        old_publisher = Publisher(
            publisher_total_article=222,
            publisher_total_fans=222)
        new_publisher = PublisherCRUD.get_publisher_by_id(db, 1)
        u_publisher = PublisherCRUD.update_publisher(db, new_publisher, old_publisher)
        print(u_publisher.publisher_name)

    # 假设 db 是 SQLAlchemy 的 Session 对象
    # db = MySQLConfig().get_redis_client()
    #
    # # 准备批量插入的数据
    # publishers_data = [
    #     {
    #         "publisher_name": "Publisher A",
    #         "publisher_url": "https://publisher-a.com",
    #         "publisher_location": "New York",
    #         "publisher_total_article": 100,
    #         "publisher_total_fans": 5000,
    #     },
    #     {
    #         "publisher_name": "Publisher B",
    #         "publisher_url": "https://publisher-b.com",
    #         "publisher_location": "London",
    #         "publisher_total_article": 200,
    #         "publisher_total_fans": 8000,
    #     },
    #     {
    #         "publisher_name": "Publisher C",
    #         "publisher_url": "https://publisher-c.com",
    #         "publisher_location": "Tokyo",
    #         # 未提供 publisher_total_article 和 publisher_total_fans，使用默认值 0
    #     },
    # ]
    #
    # # 调用批量插入方法
    # PublisherCRUD.batch_insert_publishers(db, publishers_data)

